/**
 * Created by Administrator on 2016/10/11.
 */

var localStorage = cc.sys.localStorage;
var LOCAL_STORAGE_KEYS = "LOCAL_STORAGE_KEYS";
var LOCAL_ISMD = "LIST_STATE";
var mdKey = "dks@!~";
jGame.saveData = function (key, value) {
    //cc.log("jGame.saveData[" + key + "]:" + value);
    if (value === null || value == "") return;
    // var list = jGame.getMDKeys();
    // var valueKey = jGame.MD5(value+mdKey);
    // list[jGame.MD5(key)]  = valueKey;
    // localStorage.setItem(LOCAL_ISMD, JSON.stringify(list) );
    localStorage.setItem(key, value);
    var keys = jGame.getKeys();
    if(keys.indexOf(key) < 0) {
        keys.push(key);
    }
    localStorage.setItem(LOCAL_STORAGE_KEYS, JSON.stringify(keys));
}

jGame.islocalStorageData = function(key) {
    if(localStorage.getItem(key)) {
        return true;
    }
    return false;
}

jGame.getData = function (key, defaultValue) {
    //cc.log("jGame.getData[" + key + "]:" + defaultValue);
    var value = localStorage.getItem(key);
    // if( !localStorage.getItem(LOCAL_ISMD) ){
    //     if ((value === null || value == "") && defaultValue !== undefined) return defaultValue;
    // }else {
    //     var newValueKey = jGame.MD5(value+mdKey);
    //     var oldKey = jGame.getMDKeys()[jGame.MD5(key)];
    //     if( oldKey == newValueKey ){
    //         if ((value === null || value == "") && defaultValue !== undefined) return defaultValue;
    //         return value;
    //     }else{
    //         if( oldKey == undefined ){
    //             return defaultValue;
    //         }
    //         console.log(key+"----------------------验证失败-----------------------------:>"+oldKey+"============="+newValueKey);
    //     }
    // }
    // return defaultValue;
    if ((value === null || value == "") && defaultValue !== undefined) return defaultValue;
    return value;
}

jGame.cleanData = function (key) {
    localStorage.removeItem(key);
    var keys = jGame.getKeys();
    var index = keys.indexOf(key);
    if( index >= 0 ) {
        keys.splice(index,1);
        localStorage.setItem(LOCAL_STORAGE_KEYS, JSON.stringify(keys));
    }
}
jGame.getMDKeys = function () {
    var keys;
    var value = localStorage.getItem(LOCAL_ISMD);
    if (value === null || value == "") {
        keys = {};
    }else {
        keys = JSON.parse(value);
    }
    return keys;
}

jGame.initUserDate= function () {
    for( index in jGame.getKeys() ){
        var value = localStorage.getItem(jGame.getKeys()[index]);
        jGame.saveData(jGame.getKeys()[index] , value );
    }
}

jGame.getKeys = function () {
    var keys;
    var value = localStorage.getItem(LOCAL_STORAGE_KEYS);
    if (value === null || value == "") {
        keys = [];
    }else {
        keys = JSON.parse(value);
    }
    return keys;
}